//
//  SmallDecisionsNswcViewController.m
//  SmallDecisions
//
//  Created by 李付雄 on 2025/8/20.
//

#import "SmallDecisionsNswcViewController.h"
#import "SmallDecisionsNswcResultViewController.h"

@interface SmallDecisionsNswcViewController ()
@property (nonatomic, strong) UILabel *tipLabel;
@property (nonatomic, strong) UILabel *countdownLabel;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) NSTimeInterval remainingTime;
@property (nonatomic, strong) NSDate *backgroundDate;
@property (nonatomic, strong) UILabel *contentLabel;

@property (nonatomic, strong) UIView *bottomContainerView;
@property (nonatomic, strong) AlignButton *nextBtn;
@property (nonatomic, strong) AlignButton *correntBtn;
@property (nonatomic, strong) NSMutableArray *nswcList;
@property (nonatomic, strong) NSMutableArray *correntList;
@property (nonatomic, assign) NSUInteger checkedIndex;

@end

@implementation SmallDecisionsNswcViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.title = @"你画我猜";
    [self tipLabel];
    [self contentLabel];
    [self nextBtn];
    [self correntBtn];
    [self startLoadViewData];
    self.checkedIndex = 0;
}

- (void)startLoadViewData{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSString *path = [[NSBundle mainBundle] pathForResource:@"NswcData" ofType:@"json"];
        NSData  *data  = [NSData dataWithContentsOfFile:path];
        NSArray *list = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        weakSelf(self);
        dispatch_async(dispatch_get_main_queue(), ^{
            weakself.nswcList = [list[weakself.selectIndex] copy];
            [weakself generateRandomNswc];
        });
    });
}

- (void)generateRandomNswc {
    // 开始倒计时
    self.remainingTime = [[NSDate dateWithTimeIntervalSinceNow:self.time] timeIntervalSinceDate:[NSDate date]];
    NSMutableArray *tempArray = [NSMutableArray arrayWithArray:self.nswcList];
    NSUInteger count = [tempArray count];
    for (NSInteger i = count - 1; i > 0; i--) {
        // 生成一个在0到i之间的随机数
        NSInteger n = arc4random_uniform((u_int32_t)(i + 1));
        [tempArray exchangeObjectAtIndex:i withObjectAtIndex:n];
    }
    self.nswcList = [tempArray copy];
    
    [self.contentLabel setText:self.nswcList[self.checkedIndex]];
    self.tipLabel.text = [NSString stringWithFormat:@"第%lu题",self.checkedIndex + 1];
    [self updateCountdownLabel];
    weakSelf(self);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (weakself.remainingTime > 0) {
            [weakself startTimer];
       }
    });
}

- (void)startTimer {
    // 停止现有的计时器
    [self stopTimer];
    // 创建新的计时器
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                  target:self
                                                selector:@selector(updateCountdown)
                                                userInfo:nil
                                                 repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    
}

- (void)stopTimer {
    [self.timer invalidate];
    self.timer = nil;
}

- (void)updateCountdown {
    self.remainingTime--;
    if (self.remainingTime <= 0) {
        // 倒计时结束
        [self stopTimer];
        self.countdownLabel.text = @"00:00";
        [self showResultVC];
    } else {
        // 更新倒计时显示
        [self updateCountdownLabel];
    }
}

- (void)showResultVC {
    SmallDecisionsNswcResultViewController *resultVC = [[SmallDecisionsNswcResultViewController alloc] init];
    resultVC.correntList = self.correntList;
    @weakify(self);
    resultVC.callback = ^(NSDictionary *dic) {
        if([dic[@"new"] boolValue]) {
            weak_self.checkedIndex = 0;
            [weak_self.correntList removeAllObjects];
            [weak_self generateRandomNswc];
        }
    };
    [SmallDecisionsNavigatorManager presentViewController:resultVC showNavigationBar:NO animationType:SmallDecisionsAnimationTypeAlert];    
}

- (void)updateCountdownLabel {
    NSInteger hours = self.remainingTime / 3600;
    NSInteger minutes = (self.remainingTime - hours * 3600) / 60;
    NSInteger seconds = (NSInteger)self.remainingTime % 60;
    self.countdownLabel.text = [NSString stringWithFormat:@"%02ld:%02ld",(long)minutes, (long)seconds];
}

- (NSMutableArray *)nswcList {
    if(!_nswcList) {
        _nswcList = [[NSMutableArray alloc] init];
    }
    return _nswcList;
}

- (NSMutableArray *)correntList {
    if(!_correntList) {
        _correntList = [[NSMutableArray alloc] init];
    }
    return _correntList;
}

- (UILabel *)tipLabel {
    if(!_tipLabel) {
        _tipLabel = [[UILabel alloc] init];
        _tipLabel.textColor = SmallDecisionsLineHeightColor;
        _tipLabel.font = SmallDecisionsSetFontSize(16);
        _tipLabel.textAlignment = 1;
        [self.view addSubview:_tipLabel];
        [_tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_offset(10);
            make.left.right.mas_offset(0);
            make.height.mas_offset(30);
        }];
    }
    return _tipLabel;
}

- (UILabel *)contentLabel {
    if(!_contentLabel) {
        _contentLabel = [[UILabel alloc] init];
        _contentLabel.textColor = SmallDecisionsThemeFontColor;
        _contentLabel.font = SmallDecisionsSetBoldFontSize(30);
        _contentLabel.textAlignment = 1;
        [self.view addSubview:_contentLabel];
        [_contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.tipLabel.mas_bottom);
            make.left.right.mas_offset(0);
            make.bottom.equalTo(self.bottomContainerView.mas_top);
        }];
    }
    return _contentLabel;
}


- (UIView *)bottomContainerView {
    if(!_bottomContainerView) {
        _bottomContainerView = [[UIView alloc] init];
        [self.view addSubview:_bottomContainerView];
        [_bottomContainerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.mas_offset(0);
        }];
    }
    return _bottomContainerView;
}

- (AlignButton *)nextBtn {
    if(!_nextBtn) {
        _nextBtn = [AlignButton buttonWithType:UIButtonTypeCustom];
        [_nextBtn setTitle:@"换一个" forState:UIControlStateNormal];
        [_nextBtn setTitleColor:SmallDecisionsThemeFontColor forState:UIControlStateNormal];
        [_nextBtn setTitleColor:[UIColor clearColor] forState:UIControlStateHighlighted];
        _nextBtn.titleLabel.font = SmallDecisionsSetBoldFontSize(14);
        _nextBtn.layer.cornerRadius = 25;
        _nextBtn.layer.masksToBounds = YES;
        _nextBtn.backgroundColor = SmallDecisionsSecondBgColor;
        [_nextBtn addTarget:self action:@selector(nextBtnAction) forControlEvents:UIControlEventTouchUpInside];
        [self.bottomContainerView addSubview:_nextBtn];
        [_nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(50);
            make.left.mas_offset(20);
            make.right.equalTo(self.view.mas_centerX).offset(-5);
            make.top.mas_offset(30);
            make.bottom.mas_offset(-100 - self.view.safeAreaInsets.bottom);
        }];
    }
    return _nextBtn;
}

- (void)nextBtnAction {
    self.checkedIndex += 1;
    [self.contentLabel setText:self.nswcList[self.checkedIndex]];
    self.tipLabel.text = [NSString stringWithFormat:@"第%lu题",self.checkedIndex + 1];
}

- (AlignButton *)correntBtn {
    if(!_correntBtn) {
        _correntBtn = [AlignButton buttonWithType:UIButtonTypeCustom];
        [_correntBtn setTitle:@"答对" forState:UIControlStateNormal];
        [_correntBtn setTitleColor:SmallDecisionsThemeFontColor forState:UIControlStateNormal];
        [_correntBtn setTitleColor:[UIColor clearColor] forState:UIControlStateHighlighted];
        _correntBtn.titleLabel.font = SmallDecisionsSetBoldFontSize(14);
        _correntBtn.layer.cornerRadius = 25;
        _correntBtn.layer.masksToBounds = YES;
        _correntBtn.backgroundColor = SmallDecisionsThemeColor;
        [_correntBtn addTarget:self action:@selector(correntBtnAction) forControlEvents:UIControlEventTouchUpInside];
        [self.bottomContainerView addSubview:_correntBtn];
        [_correntBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.top.width.mas_equalTo(self.nextBtn);
            make.left.equalTo(self.view.mas_centerX).offset(5);
        }];
    }
    return _correntBtn;
}

- (void)correntBtnAction {
    [self.correntList addObject:self.contentLabel.text];
    self.checkedIndex += 1;
    [self.contentLabel setText:self.nswcList[self.checkedIndex]];
    self.tipLabel.text = [NSString stringWithFormat:@"第%lu题",self.checkedIndex + 1];
}

- (UIView *)setCenterBarView {
    UIView *centerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 34)];
    centerView.backgroundColor = SmallDecisionsSecondBgColor;
    centerView.layer.cornerRadius = 17;
    centerView.layer.masksToBounds = YES;
    UILabel *countdownLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 34)];
    countdownLabel.textColor = SmallDecisionsThemeFontColor;
    countdownLabel.font = SmallDecisionsSetFontSize(20);
    countdownLabel.textAlignment = 1;
    countdownLabel.text = @"00:00";
    [centerView addSubview:countdownLabel];
    self.countdownLabel = countdownLabel;
    return centerView;
}

#pragma mark - 处理后台状态
- (void)appDidEnterBackground:(NSNotification *)notification {
    self.backgroundDate = [NSDate date];
}

- (void)appWillEnterForeground:(NSNotification *)notification {
    if (self.backgroundDate && self.timer) {
        NSDate *now = [NSDate date];
        NSTimeInterval backgroundTime = [now timeIntervalSinceDate:self.backgroundDate];
        self.remainingTime -= backgroundTime;
        if (self.remainingTime <= 0) {
            [self stopTimer];
            self.countdownLabel.text = @"00:00";
            [self showResultVC];
        } else {
            [self updateCountdownLabel];
        }
    }
    self.backgroundDate = nil;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 注册通知，处理应用进入后台的情况
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appDidEnterBackground:)
                                                 name:UIApplicationDidEnterBackgroundNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appWillEnterForeground:)
                                                 name:UIApplicationWillEnterForegroundNotification
                                               object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)backBarButtonAction:(UIView *)view {
    [self stopTimer];
    [SmallDecisionsAlertViewController showAlertWithTitle:nil message:@"确定退出该游戏吗？" cancelText:@"取消" otherText:@"确定" dismissCompletion:^(SMALL_DECISIONS_PROJECT_ALERT_HANDLE_EVENTS event) {
        if(event == SMALL_DECISIONS_PROJECT_ALERT_HANDLE_EVENTS_CANCEL) {
            [self startTimer];
        } else {
            [SmallDecisionsNavigatorManager popViewControllerAnimated:YES];
        }
    }];
}

- (void)dealloc {
    [self stopTimer];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end
